﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using System.IO;

namespace JiuMeiMall.PMethod.SafeEncrypt
{
    public static class NativeEncrypt
    {
        /// <summary>
        /// 密钥
        /// </summary>
        static readonly byte[] KEY = new byte[] { 179, 240, 237, 48, 119, 108, 152, 16, 157, 120, 26, 36, 220, 139, 247, 83 };

        /// <summary>
        /// MD5加密
        /// </summary>
        /// <param name="value">源串</param>
        /// <returns>加密串</returns>
        public static string MD5_Encrypt(string value)
        {
            byte[] result = Encoding.UTF8.GetBytes(value);
            System.Security.Cryptography.MD5 md5 = new MD5CryptoServiceProvider();
            return BitConverter.ToString(md5.ComputeHash(result)).Replace("-", "");
        }

        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="source">源串</param>
        /// <returns>加密串</returns>
        public static string Encrypt(string source)
        {
            byte[] bs = Encoding.UTF8.GetBytes(source);
            RijndaelManaged rDel = new RijndaelManaged();
            rDel.Key = KEY;
            rDel.Mode = CipherMode.ECB;
            rDel.Padding = PaddingMode.PKCS7;
            ICryptoTransform cTransform = rDel.CreateEncryptor();
            return Convert.ToBase64String(cTransform.TransformFinalBlock(bs, 0, bs.Length));
        }

        /// <summary>
        /// 解密,失败返回NULL
        /// </summary>
        /// <param name="source">源串</param>
        /// <returns>解密串</returns>
        public static string Decrypt(string source)
        {
            try
            {
                byte[] bs = Convert.FromBase64String(source);
                RijndaelManaged rDel = new RijndaelManaged();
                rDel.Key = KEY;
                rDel.Mode = CipherMode.ECB;
                rDel.Padding = PaddingMode.PKCS7;
                ICryptoTransform cTransform = rDel.CreateDecryptor();
                return Encoding.UTF8.GetString(cTransform.TransformFinalBlock(bs, 0, bs.Length));
            }
            catch
            {
                return null;
            }
        }
    }
}
